
package com.ttomato.game.gamedev2d;

import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import com.ttomato.game.framework.Game;
import com.ttomato.game.framework.Input;
import com.ttomato.game.framework.Screen;
import com.ttomato.game.framework.Input.TouchEvent;
import com.ttomato.game.framework.gl.Vertices;
import com.ttomato.game.framework.impl.GLGame;
import com.ttomato.game.framework.impl.GLGraphics;
import com.ttomato.game.framework.math.Vector2;

public class CannonTest extends GLGame {

    @Override
    public Screen getStartScreen() {
        return new CannonScreen(this);
    }

    class CannonScreen extends Screen {

        static final float FRUSTUM_WIDTH = 4.8f;
        static final float FRUSTUM_HEIGHT = 3.2f;
        GLGraphics mGlGraphics;
        Vertices mVertices;
        Vector2 mCannonPos = new Vector2(2.4f, 0.5f);
        float mCannonAngle = 0f;
        Vector2 mTouchPos = new Vector2();

        public CannonScreen(Game game) {
            super(game);
            mGlGraphics = ((GLGame) game).getGLGraphics();
            mVertices = new Vertices(mGlGraphics, 3, 0, false, false);
            mVertices.setVertices(new float[] {
                    -0.5f, -0.5f,
                    0.5f, 0.0f,
                    -0.5f, 0.5f
            }, 0, 6);
        }

        @Override
        public void update(float deltaTime) {
            List<TouchEvent> events = mGame.getInput().getTouchEvents();
            mGame.getInput().getKeyEvents();

            int len = events.size();
            TouchEvent event;
            for (int i = 0; i < len; i++) {
                event = events.get(i);
                mTouchPos.mX = (event.x / (float) mGlGraphics.getWidth()) * FRUSTUM_WIDTH;
                mTouchPos.mY = (1 - event.y / (float) mGlGraphics.getHeight()) * FRUSTUM_HEIGHT;
                mCannonAngle = mTouchPos.sub(mCannonPos).angle();
            }
        }

        @Override
        public void present(float deltaTime) {
            GL10 gl = mGlGraphics.getGl();
            gl.glViewport(0, 0, mGlGraphics.getWidth(), mGlGraphics.getHeight());
            gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
            gl.glMatrixMode(GL10.GL_PROJECTION);
            gl.glLoadIdentity();
            gl.glOrthof(0, FRUSTUM_WIDTH, 0, FRUSTUM_HEIGHT, 1, -1);

            gl.glMatrixMode(GL10.GL_MODELVIEW);
            gl.glLoadIdentity();

            gl.glTranslatef(mCannonPos.mX, mCannonPos.mY, 0);
            gl.glRotatef(mCannonAngle, 0, 0, 1);
            mVertices.bind();
            mVertices.draw(GL10.GL_TRIANGLES, 0, 3);
            mVertices.unbind();
        }

        @Override
        public void pause() {
            // TODO Auto-generated method stub

        }

        @Override
        public void resume() {
            // TODO Auto-generated method stub

        }

        @Override
        public void dispose() {
            // TODO Auto-generated method stub

        }
    }

}
